package com.zhx.zaxiang.controller;

import com.alibaba.excel.EasyExcel;
import com.zhx.zaxiang.excel.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@RestController
public class EasyExcelController {

    @PostMapping("/")
    public void getExcel(HttpServletResponse response) throws IOException {
        //调用业务，构造模板列表数据
        List<User> listModel = getUsers();
        //写入数据
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode("users.xlsx", "UTF-8"));

        Set<String> excludeColumnFiledNames = new HashSet<String>();
        excludeColumnFiledNames.add("date");

        //使用的easyexcel工具就这一行
        EasyExcel.write(out, User.class)
                .excludeColumnFiledNames(excludeColumnFiledNames).
                autoCloseStream(true).sheet("信息列表").doWrite(listModel);
        out.flush();
    }

    private List<User> getUsers() {
        List<User> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setDate(new Date());
            user.setDoubleData((double) (111 + i));
            user.setString("xiaole");
            user.setString2("xiaole2");
            list.add(user);
        }
        return list;
    }

    /**
     * 导出文件名乱码问题
     * @return
     */
    private void reformResponse(HttpServletResponse response,String fileName) throws UnsupportedEncodingException {
       response.setContentType("application/vnd.openxmlformats-offocaedocument.spreadsheetml.sheet");
       response.setCharacterEncoding("utf-8");
       if (!fileName.contains(".")){
           fileName=fileName+".xlsl";
       }
        String encodeName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition","attachment;filename="+encodeName+";filename*=utf-8''"+encodeName);
    }
}
